﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@algo-plus.co.uk website<http://www.algo-plus.co.uk/>
using System;
using System.Linq;
using FinPlusCompCore;
using FinPlusAssembler;
using FinPlusInterfaces;
using s = FinPlusBaseMath.Statistics;

namespace FinPlusCompAlgo
{
    public class AlgPlusVar : FinPlusComponent
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }
        [State(Test = true)]
        public override string TestString { get { return Adapter.ToString(); } }

        public override IPods Adapter { get { return _adapter; } }

        private enum Params { Variance }
        private IFinPlusComp _feed;
        private readonly IPods _adapter;
        private readonly string _name, _value;
        private readonly short _from, _decimalPlaces;
          
        //construct
        public AlgPlusVar(IFinPlusComp feed, short from, string name, string value, short decimalPlaces) 
        {
            _feed = feed;
            _from = from;
            _name = name;
             _value = value;
            _decimalPlaces = decimalPlaces;
            _adapter = IOC.New<IPods>();
            IsValid = true;
            CalcVar(_feed);
        }

        //common control interface
        public override void CmdExecute(IPod command)
        {
            IsValid = false;
            throw new NotImplementedException();
        }

        public override void Dispose()
        {
            if (_feed != null)
                _feed.Dispose();
        }

        //private
        private void CalcVar(IFinPlusComp feed)
        {
            _feed = feed;
            var res = feed.Adapter.ToList(_name, _value).First().Where(i => i.Index >= _from);
            var pod = IOC.New<IPod>(Params.Variance.ToString(), "-1");
            var var = s.Variance(res.Select(i => (double)i.Object).ToArray<double>());
            pod[Params.Variance.ToString()] = Math.Round(var, _decimalPlaces);
            _adapter.Add(pod);
        }
    }
}
